package com.dwjm.exam.stu_login;

import com.dwjm.exam.pojo.Student;
import com.dwjm.utils.CommonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginHandler extends HttpServlet {
    private LoginDao loginDao = new LoginDaoImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String userType = req.getParameter("userType"); // "student" 或 "admin"

        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            resp.getWriter().write("N");
            return;
        }

        // 根据用户类型处理登录
        if ("student".equalsIgnoreCase(userType)) {
            handleStudentLogin(username, password, resp);
        } else if ("admin".equalsIgnoreCase(userType)) {
            handleAdminLogin(username, password, resp);
        } else {
            resp.getWriter().write("N");
        }
    }

    private void handleStudentLogin(String username, String password, HttpServletResponse resp) throws IOException {
        Student student = loginDao.studentLogin(username, password);
        if (student != null) {
            // 登录成功，可以在这里设置session等操作
            resp.getWriter().write("Y");
        } else {
            resp.getWriter().write("N");
        }
    }

    private void handleAdminLogin(String username, String password, HttpServletResponse resp) throws IOException {
        boolean isAdmin = loginDao.adminLogin(username, password);
        if (isAdmin) {
            // 管理员登录成功
            resp.getWriter().write("Y");
        } else {
            resp.getWriter().write("N");
        }
    }
}